package io.framework.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.framework.common.page.PageData;
import io.framework.common.service.impl.BaseServiceImpl;
import io.framework.common.utils.ConvertUtils;
import io.framework.modules.security.user.SecurityUser;
import io.framework.modules.security.user.UserDetail;
import io.framework.modules.sys.dao.StatuteDao;
import io.framework.modules.sys.dto.StatuteDTO;
import io.framework.modules.sys.entity.StatuteEntity;
import io.framework.modules.sys.enums.SuperAdminEnum;
import io.framework.modules.sys.service.StatuteService;
import io.framework.modules.sys.service.SysDeptService;
import io.framework.modules.sys.service.SysRoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 系统用户
 * 
 *
 */
@Service
public class StatuteServiceImpl extends BaseServiceImpl<StatuteDao, StatuteEntity> implements StatuteService {
	@Autowired
	private SysRoleUserService sysRoleUserService;
	@Autowired
	private SysDeptService sysDeptService;

	@Override
	public PageData<StatuteDTO> page(Map<String, Object> params) {
		//转换成like
		paramsToLike(params, "bt");
		//分页
		IPage<StatuteEntity> page = getPage(params, "", false);
		//查询
		List<StatuteEntity> list = baseDao.getList(params);

		return getPageData(list, page.getTotal(), StatuteDTO.class);
	}

	@Override
	public List<StatuteDTO> list(Map<String, Object> params) {
		//普通管理员，只能查询所属部门及子部门的数据
		UserDetail user = SecurityUser.getUser();
		if(user.getSuperAdmin() == SuperAdminEnum.NO.value()) {
			params.put("deptIdList", sysDeptService.getSubDeptIdList(user.getDeptId()));
		}

		List<StatuteEntity> entityList = baseDao.getList(params);

		return ConvertUtils.sourceToTarget(entityList, StatuteDTO.class);
	}

	@Override
	public StatuteDTO get(Long id) {
		StatuteEntity entity = baseDao.getById(id);

		return ConvertUtils.sourceToTarget(entity, StatuteDTO.class);
	}

	@Override
	public StatuteDTO getByUsername(String username) {
		StatuteEntity entity = baseDao.getByUsername(username);
		return ConvertUtils.sourceToTarget(entity, StatuteDTO.class);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(StatuteDTO dto) {
		StatuteEntity entity = ConvertUtils.sourceToTarget(dto, StatuteEntity.class);

		insert(entity);


	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void update(StatuteDTO dto) {
		StatuteEntity entity = ConvertUtils.sourceToTarget(dto, StatuteEntity.class);

		//更新用户
		updateById(entity);
	}

	@Override
	public void delete(Long[] ids) {
		//删除用户
		baseDao.deleteBatchIds(Arrays.asList(ids));
	}


}
